package http_backup_mode

import (
	"backup-http/common"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func DoRequestWithBackup(client *http.Client, req *http.Request, backUpTime time.Duration) ([]byte, error) {
	// 请求通道
	call := make(chan *common.CommonResp, 2)

	// 发起第一次请求
	go func() {
		resp1, err1 := client.Do(req)
		call <- &common.CommonResp{
			Resp: resp1,
			Err:  err1,
		}
	}()

	// 用于控制主请求的定时器
	t := time.NewTimer(backUpTime)
	defer t.Stop()

	// 处理响应结果
	handleBackupResp := func(backupResp *common.CommonResp) ([]byte, error) {
		defer backupResp.Resp.Body.Close()
		if backupResp.Err != nil {
			return nil, backupResp.Err
		}
		body, err := ioutil.ReadAll(backupResp.Resp.Body)
		if err != nil {
			return nil, err
		}
		return body, nil
	}

	select {
	case backupResp := <-call:
		return handleBackupResp(backupResp)
	case <-t.C:
		// 超过等待时间，开启备份请求
		log.Printf("Primary request %s in %s didn't fininsh, starting backup request.", req.Host, backUpTime)
	}

	go func() {
		resp2, err2 := client.Do(req)
		call <- &common.CommonResp{
			Resp: resp2,
			Err:  err2,
		}
	}()

	backupResp := <-call
	return handleBackupResp(backupResp)
}
